package main;

import java.awt.Component;
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

public class NormalTable extends JTable {

//	this calss does 2 things: 1 fit the width of column to the max width of each cell, 2 set the total width 

	public NormalTable(AbstractTableModel tableModel) {
		super(tableModel);
		fitColumnWidths();
		double width = getPreferredSize().width;
		double scrollWith = getPreferredScrollableViewportSize().width;
		double realWidth = Math.max(width, scrollWith);
		double height = getPreferredSize().getHeight();
		setPreferredScrollableViewportSize(new Dimension((int) realWidth,
				(int) height));

	}

	/**
	 * done
	 */
	private void fitColumnWidths() {
		for (int col = 0; col < getColumnCount(); col++) {
			int maxwidth = 0;
			// ### get header width
			TableCellRenderer headRend = getTableHeader().getDefaultRenderer();
			Object headValue = getColumnModel().getColumn(col).getHeaderValue();
			Component headComp = headRend.getTableCellRendererComponent(this,
					headValue, false, false, -1, col);
			int headWidth = headComp.getPreferredSize().width;
			maxwidth = headWidth;
			// get max width of col from all row
			for (int row = 0; row < getRowCount(); row++) {
				TableCellRenderer rend = getCellRenderer(row, col);
				Object value = getValueAt(row, col);
				Component comp = rend.getTableCellRendererComponent(this,
						value, false, false, row, col);
				maxwidth = Math.max(comp.getPreferredSize().width, maxwidth);
			}
			// end
			TableColumn column = getColumnModel().getColumn(col);
			column.setPreferredWidth(maxwidth + 10);
		}
	}

}
